<template>
  <div class="workspace-box">
    <splitpanes style="height: 100%; width: 100%">
      <!-- 左侧内容 -->
      <pane size="20" min-size="20" max-size="80">
        <div class="left-pane">
          <div class="scrollable-content">
            <Database
              :databases="databases"
              :onDatabaseAction="onDatabaseAction"
              @onLoadData="handleLoadData"
              @onContextMenuClick="handleContextMenu"
              @onDatabaseSelect="onDatabaseSelect"
              @onTableSelect="onTableSelect"
            />
          </div>
        </div>
      </pane>
      <!-- 右侧内容 -->
      <pane>
        <div class="pane-content right-pane">
          <Tabs
            style="width: 100%"
            v-model:activeKey="activeTabKey"
            size="middle"
            type="editable-card"
            @edit="onEdit"
            :tabBarGutter="5"
          >
            <template #addIcon>
              <PlusOutlined />
              <span class="tabs-new-tab">&nbsp;新建查询</span>
            </template>
            <!-- 固定tab页，表信息 -->
            <Tabs.TabPane key="tableInfo" :closable="false">
              <template #tab>
                <span>
                  <TableOutlined />
                  表信息
                </span>
              </template>
              <template #default>
                <!--  -->
                <div>
                  <div>
                    <!-- 右侧表格，展示一个表格的字段列表 -->
                    <!-- 这里显示数据源以及当前选择数据库，并且显示行与下面的form行距合适    -->
                    <div style="margin-bottom: 10px">
                      <span>
                        当前数据源： <Tag color="green">{{ getDsName() }} </Tag></span
                      >&nbsp;&nbsp;&nbsp;&nbsp;
                      <span v-if="selectedDatabaseName">
                        当前数据库：
                        <Tag color="green"> {{ selectedDatabaseName }}</Tag></span
                      >
                      <Button
                        v-if="selectedDatabaseName"
                        @click="onCreateTableClick"
                        type="dashed"
                        size="small"
                      >
                        <PlusOutlined />
                        新建表
                      </Button>
                    </div>
                  </div>
                  <!-- 只有selectedTableObject.name不为空的时候，才显示右侧内容 -->
                  <Card v-if="selectedTableObject.name">
                    <div style="margin-bottom: 5px">
                      表：<Tag color="red"> {{ selectedTableObject.name }}</Tag>
                    </div>
                    <Tabs
                      size="small"
                      v-model:activeKey="tableActiveKey"
                      type="card"
                      @change="onTableTabsChange"
                    >
                      <Tabs.TabPane key="tableEdit" tab="编辑表">
                        <TableEditor
                          v-model:modelValue="tableConfig"
                          @preview="tablePreview"
                          :onTableAction="onTableAction"
                        />
                      </Tabs.TabPane>
                      <Tabs.TabPane key="tableRelationships" tab="关联关系">
                        <div>
                          <div style="margin-bottom: 10px">
                            <Button type="primary" @click="onAddTableRelationship"
                              >添加关联</Button
                            >
                            <!-- 添加关联弹窗 -->
                            <Modal
                              v-model:open="addTableRelationshipModalVisible"
                              title="添加关联"
                              width="800px"
                              @ok="onAddTableRelationshipOk"
                            >
                              <TableRelationshipForm
                                :isAddTableRelationship="isAddTableRelationship"
                                :model="addTableRelationshipFormModel"
                                :sourceTable="selectedTableObject"
                                :tableList="tableList.items"
                                :sourceFields="sourceTableFieldsList"
                                :targetFields="targetTableFieldsList"
                                :columns="tableRelationshipsEditColumns"
                                @addRelationshipField="onAddTableRelationshipField"
                                @deleteRelationshipField="onDeleteTableRelationshipField"
                                @targetTableChange="onTargetTableChange"
                              />
                            </Modal>
                          </div>
                          <div>
                            <Table
                              size="small"
                              :dataSource="tableRelationshipsDataSource"
                              :columns="tableRelationshipsColumns"
                              bordered
                            >
                              <template #bodyCell="{ column, text, record }">
                                <template v-if="column.dataIndex === 'operations'">
                                  <a @click="onEditTableRelationship(record)">编辑</a>
                                  <Divider type="vertical" />
                                  <Popconfirm
                                    title="Sure to delete?"
                                    @confirm="onDeleteTableRelationship(record)"
                                  >
                                    <a>删除</a>
                                  </Popconfirm>
                                </template>
                              </template>
                            </Table>
                          </div>
                        </div>
                      </Tabs.TabPane>
                      <Tabs.TabPane key="tablePermissions" tab="权限">
                        <div>
                          <div style="margin-bottom: 10px">
                            <Button type="primary" @click="onAddTablePermission"
                              >添加权限配置</Button
                            >
                            <!-- 添加关联弹窗 -->
                            <Modal
                              v-model:open="addTablePermissionModalVisible"
                              width="800px"
                              title="添加权限配置"
                              @ok="onAddTablePermissionOk"
                            >
                              <PermissionForm
                                :model="addTablePermissionFormModel"
                                :tableObject="selectedTableObject"
                                :fields="selectedTableFieldsList"
                                @addPreset="onAddTablePermissionInsertPreset"
                                @removePreset="onDeleteTablePermissionInsertPreset"
                              />
                            </Modal>
                          </div>
                          <div>
                            <Table
                              size="small"
                              :dataSource="tablePermissionsDataSource"
                              :columns="tablePermissionsColumns"
                            />
                          </div>
                        </div>
                      </Tabs.TabPane>
                    </Tabs>
                  </Card>
                </div>
              </template>
            </Tabs.TabPane>

            <Tabs.TabPane
              v-for="pane in panes"
              :key="pane.key"
              :tab="pane.title"
              :closable="pane.closable"
            >
              <div v-if="pane.type === 'tableCreator'" class="pane-content">
                <TableEditor
                  v-model:modelValue="pane.data"
                  @preview="tablePreview"
                  @create="onCloseCreateTable(pane)"
                  :onTableAction="onTableAction"
                />
              </div>
              <div v-else-if="pane.type === 'newQuery'">
                <QueryPanel
                  :data="pane.data"
                  :databases="databases"
                  :onQueryAction="onEditAction"
                />
              </div>
            </Tabs.TabPane>
          </Tabs>
        </div>
      </pane>
    </splitpanes>

    <Modal v-model:open="previewModelVisible" title="预览" :width="800">
      <TableEditor v-model:modelValue="tableConfig" @preview="tablePreview" />
    </Modal>
  </div>
</template>

<script setup lang="tsx">
import { reactive, ref, VueElement } from "vue";

import {
  dropTable,
  execRawSql,
  getDatabasesList,
  getFieldsList,
  getTableInfo,
  getTableList,
  IFieldObject,
  lspComplete,
  updateTable,
  createTable,
  getTableRelList,
  addTableRel,
  deleteTableRel,
  updateTableRel,
} from "@/api/goMyAdmin";
import { useI18n } from "@/hooks/web/useI18n";
import { sleep } from "@/utils";
import { DatabaseOutlined, PlusOutlined, TableOutlined } from "@ant-design/icons-vue";
import {
  Button,
  Card,
  ItemType,
  message,
  Modal,
  Table,
  Tabs,
  Tag,
  Popconfirm,
  Divider,
} from "ant-design-vue";
import { Pane, Splitpanes } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import { useRoute } from "vue-router";
import Database from "./component/Database.vue";
import FieldList from "./component/FieldList.vue";
import TableEditor from "./component/TableEditor.vue";
import PermissionForm from "./component/table-permission/PermissionForm.vue";
import TableRelationshipForm from "./component/table-relationship/TableRelationshipForm.vue";
import QueryPanel from "./component/query-panel/QueryPanel.vue";

const { t } = useI18n();
const route = useRoute();

function getItem(
  label: VueElement | string,
  key: string,
  icon?: any,
  children?: ItemType[],
  type?: "group"
): ItemType {
  return {
    key,
    icon,
    children,
    label,
    type,
  } as ItemType;
}

const databaseItemsTreeList = ref<any[]>([]);

const databaseItemsList = ref<ItemType[]>([]);

const selectedDatabaseName = ref("");
const selectedTableObject = ref<TableItemObject>({} as any);
const selectedTableFieldsList = ref<any[]>([]);
const formModel = ref({
  name: "",
  comment: "",
  engine: "InnoDB",
});

/** 左侧数据库列表选择click事件 */
const loadDabaseTableList = async (databaseName: string) => {
  tableList.items = [];
  fieldListRef.value?.clearData();
  const r = await getTableList({ dsId: getDsId(), databaseName });
  await sleep(100);
  // console.log(r);
  tableList.items = r.tables;
};

const onDatabaseSelect = async (item) => {
  selectedDatabaseName.value = item.name;
  fieldListRef.value?.clearData();
  selectedTableObject.value = {} as any;
  selectedTableFieldsList.value = [];

  loadDabaseTableList(item.name);
};

const onTableSelect = async (item: { database: string; name: string }) => {
  selectedDatabaseName.value = item.database;
  selectedTableObject.value = item;
  onClickSelectOneTable(item);
  loadDabaseTableList(item.database);

  loadTableRelationships(item.name);
};

const databases = ref<any>([]);

async function initGetDatabasesList() {
  const dsId = getDsId();

  const list = await getDatabasesList({ dsId });
  if (list.length > 0) {
    databaseItemsList.value = list.map((item) => {
      return getItem(item.name, item.name, () => <DatabaseOutlined />);
    });

    databaseItemsTreeList.value = list.map((item) => {
      return { key: item.name, title: item.name };
    });
  }

  databases.value = list;
  selectedTableObject.value = {} as any;
  selectedTableFieldsList.value = [];
  console.log(list);
  console.log(databaseItemsList.value);
  console.log(databaseItemsTreeList.value);
}

/** tabs当前激活的标签 */
const activeTabKey = ref("tableInfo");

const getRandomKey = () => {
  return `newTab${new Date().getTime()}`;
};

type paneObject = {
  type: "tableCreator" | "newQuery";
  title: string;
  key: string;
  closable: boolean;
  data:
    | {
        dsId: number;
        dsName: string;
        databaseName: string;
      }
    | {
        dsId: number;
        databaseName: string;
        name: string;
        comment: string;
        engine: string;
        columns: IFieldObject[];
      };
};
const panes = ref<paneObject[]>([]);

/** tab标签添加或删除事件 */
const onEdit = async (key, action: "add" | "remove") => {
  if (action === "add") {
    const dbName = selectedDatabaseName.value;
    const panel: paneObject = {
      type: "newQuery",
      title: dbName + " - 新建查询",
      // content: 'Content of new Tab',
      key: getRandomKey(),
      closable: true,
      data: {
        dsId: getDsId(),
        dsName: getDsName(),
        databaseName: dbName,
      },
    };
    panes.value.push(panel);
    activeTabKey.value = panel.key;
  } else {
    panes.value = panes.value.filter((pane) => pane.key !== key);
    activeTabKey.value = "tableInfo";
  }
  console.log(key, action);
};

/** table info start */
const tableActiveKey = ref("tableEdit");
const tableRelationshipsColumns = ref<any[]>([
  {
    title: "ID",
    dataIndex: "id",
    key: "id",
    width: 10,
  },
  {
    title: "关联名称",
    dataIndex: "name",
    key: "name",
    width: 50,
  },
  {
    title: "数据库",
    dataIndex: "database",
    key: "database",
    width: 50,
  },
  {
    title: "来源表",
    dataIndex: "sourceTable",
    key: "sourceTable",
    width: 100,
  },
  {
    title: "目标表",
    dataIndex: "targetTable",
    key: "targetTable",
    width: 100,
  },
  {
    title: "类型", // object， array
    dataIndex: "type",
    key: "type",
    width: 10,
  },
  {
    title: "关联",
    dataIndex: "relationships",
    key: "relationships",
    width: 200,
  },
  {
    title: "操作",
    dataIndex: "operations",
    key: "operations",
    width: 100,
  },
]);
const tableRelationshipsEditColumns = ref<any[]>([
  {
    title: "源字段",
    dataIndex: "sourceTableField",
    key: "sourceTableField",
    width: 200,
  },
  {
    title: "目标字段",
    dataIndex: "targetTableField",
    key: "targetTableField",
    width: 200,
  },
  {
    title: "操作",
    dataIndex: "operations",
    key: "operations",
  },
]);
const tableRelationshipsDataSource = ref<any[]>([]);
const addTableRelationshipModalVisible = ref(false);
const addTableRelationshipFormModel = ref<{
  id: number | null;
  name: string;
  sourceTable: string;
  targetTable: string;
  type: string;
  relationships: any[];
}>({
  id: null,
  name: "",
  sourceTable: "",
  targetTable: "",
  type: "object",
  relationships: [] as any[],
});
// addTableRelationshipFormModel初始化函数
const initAddTableRelationshipFormModel = async () => {
  addTableRelationshipFormModel.value = {
    id: null,
    name: "",
    sourceTable: selectedTableObject.value.name || "",
    targetTable: "",
    type: "object",
    relationships: [],
  };
  targetTable.value = "";
  targetTableFieldsList.value = [];
};

const sourceTableFieldsList = ref<any[]>([]);
const targetTable = ref("");
const targetTableFieldsList = ref<any[]>([]);
const onAddTableRelationshipField = async () => {
  console.log("添加关联字段");

  // 如果targetTable为空，则不添加
  if (targetTable.value === "") {
    message.error("目标表不能为空");
    return;
  }

  addTableRelationshipFormModel.value.relationships.push({
    sourceTableField: "",
    targetTableField: "",
  });
};
const onDeleteTableRelationshipField = async (index: number) => {
  console.log("删除关联字段", index);
  addTableRelationshipFormModel.value.relationships.splice(index, 1);
};

const isAddTableRelationship = ref(false);
const onAddTableRelationship = async () => {
  console.log("添加关联");
  isAddTableRelationship.value = true;
  // sourceTableFieldsList
  const fields = await getFieldsList({
    dsId: getDsId(),
    databaseName: selectedDatabaseName.value,
    tableName: selectedTableObject.value.name || "",
  });
  sourceTableFieldsList.value = fields;
  addTableRelationshipModalVisible.value = true;

  initAddTableRelationshipFormModel();
};

const onTargetTableChange = async (value: string) => {
  // 如果是清空，则不进行查询，并且清空targetTableFieldsList
  if (value === "") {
    targetTableFieldsList.value = [];
    return;
  }

  targetTable.value = value;
  const fields = await getFieldsList({
    dsId: getDsId(),
    databaseName: selectedDatabaseName.value,
    tableName: targetTable.value,
  });
  targetTableFieldsList.value = fields;
};

const loadTableRelationships = async (tableName: string) => {
  const r = await getTableRelList({
    dsId: getDsId(),
    database: selectedDatabaseName.value,
    table: tableName,
  });

  if (!r || r.length === 0) {
    tableRelationshipsDataSource.value = [];
    return;
  }

  // 将结果集转换成tableRelationshipsColumns中name对应的数据
  let tableRelationshipsList = r.map((item) => {
    return {
      id: item.id,
      name: item.name,
      database: item.database,
      sourceTable: item.sourceTable,
      targetTable: item.targetTable,
      type: item.type,
      relationships: JSON.stringify(item.relationships),
    };
  });

  tableRelationshipsDataSource.value = tableRelationshipsList;
};

const onAddTableRelationshipOk = async () => {
  console.log("添加关联确定");
  // 打印addTableRelationshipFormModel
  console.log(JSON.stringify(addTableRelationshipFormModel.value));
  if (isAddTableRelationship.value) {
    await addTableRel({
      datasourceId: getDsId(),
      database: selectedDatabaseName.value,
      name: addTableRelationshipFormModel.value.name,
      sourceTable: selectedTableObject.value.name || "",
      targetTable: addTableRelationshipFormModel.value.targetTable,
      type: addTableRelationshipFormModel.value.type,
      relationships: addTableRelationshipFormModel.value.relationships,
    });
    message.success("添加关联成功");
  } else {
    await updateTableRel({
      id: addTableRelationshipFormModel.value?.id,
      relationships: addTableRelationshipFormModel.value.relationships,
    });
    message.success("修改关联成功");
  }

  loadTableRelationships(addTableRelationshipFormModel.value.sourceTable);

  addTableRelationshipModalVisible.value = false;
};

const onEditTableRelationship = async (record: any) => {
  console.log("编辑关联", record);
  // 打印addTableRelationshipFormModel
  console.log(JSON.stringify(record));
  isAddTableRelationship.value = false;

  const srcFields = await getFieldsList({
    dsId: getDsId(),
    databaseName: selectedDatabaseName.value,
    tableName: selectedTableObject.value.name || "",
  });
  sourceTableFieldsList.value = srcFields;

  const tarFields = await getFieldsList({
    dsId: getDsId(),
    databaseName: selectedDatabaseName.value,
    tableName: record.targetTable,
  });
  targetTable.value = record.targetTable;
  targetTableFieldsList.value = tarFields;

  addTableRelationshipFormModel.value = {
    id: record.id,
    name: record.name,
    sourceTable: record.sourceTable,
    targetTable: record.targetTable,
    type: record.type,
    relationships: JSON.parse(record.relationships),
  };

  addTableRelationshipModalVisible.value = true;
};

const onDeleteTableRelationship = async (record: any) => {
  console.log("删除关联", record);
  await deleteTableRel({
    dsId: getDsId(),
    id: record.id,
  });
  message.success("删除关联成功");
  loadTableRelationships(selectedTableObject.value.name || record.sourceTable);
};

/** table info end */

/** table permission start */
// 权限
const tablePermissionsColumns = ref<any[]>([
  {
    title: "角色",
    dataIndex: "role",
    key: "role",
  },
  {
    title: "Insert",
    dataIndex: "insert",
    key: "insert",
  },
  {
    title: "Select",
    dataIndex: "select",
    key: "select",
  },
  {
    title: "Update",
    dataIndex: "update",
    key: "update",
  },
  {
    title: "Delete",
    dataIndex: "delete",
    key: "delete",
  },
]);
const tablePermissionsDataSource = ref<any[]>([]);
const addTablePermissionModalVisible = ref<boolean>(false);
const addTablePermissionFormModel = ref<any>({
  name: "",
  table: "",
  /** select */
  // 行查询权限校验
  selectCheck: "{}",
  // 行查询行数限制
  selectLimit: 20,
  // 列查询权限
  selectColumns: [],
  // 列查询预设
  selectPresets: [],
  /** insert */
  // 行插入权限校验
  insertCheck: "{}",
  // 列插入权限
  insertColumns: [],
  // 列插入预设
  insertPresets: [],
  /** update */
  // 行更新权限校验
  updateCheck: "{}",
  // 列更新权限
  updateColumns: [],
  // 列更新预设
  updatePresets: [],
});

const onAddTablePermission = async () => {
  console.log("onAddTablePermission");
  addTablePermissionModalVisible.value = true;

  initAddTablePermissionFormModel();
};

const initAddTablePermissionFormModel = async () => {
  addTablePermissionFormModel.value = {
    name: "",
    table: "",
    /** select */
    // 行查询权限校验
    selectCheck: "{}",
    // 行查询行数限制
    selectLimit: 20,
    // 列查询权限
    selectColumns: [],
    // 列查询预设
    selectPresets: [],
    /** insert */
    // 行插入权限校验
    insertCheck: "{}",
    // 列插入权限
    insertColumns: [],
    // 列插入预设
    insertPresets: [],
    /** update */
    // 行更新权限校验
    updateCheck: "{}",
    // 列更新权限
    updateColumns: [],
    // 列更新预设
    updatePresets: [],
  };
};

const onAddTablePermissionOk = async () => {
  console.log("onAddTablePermissionOk");
  console.log(addTablePermissionFormModel.value);
};

const onAddTablePermissionInsertPreset = async () => {
  console.log("onAddTablePermissionInsertPreset");
  addTablePermissionFormModel.value.insertPresets.push({
    column: "",
    presetType: "static",
    presetValue: "",
  });
};
const onDeleteTablePermissionInsertPreset = async (index: number) => {
  console.log("onDeleteTablePermissionInsertPreset", index);
  addTablePermissionFormModel.value.insertPresets.splice(index, 1);
};

const onAddTablePermissionUpdatePreset = async () => {
  console.log("onAddTablePermissionUpdatePreset");
  addTablePermissionFormModel.value.updatePresets.push({
    column: "",
    presetType: "static",
    presetValue: "",
  });
};
const onDeleteTablePermissionUpdatePreset = async (index: number) => {
  console.log("onDeleteTablePermissionUpdatePreset", index);
  addTablePermissionFormModel.value.updatePresets.splice(index, 1);
};

/** table permission end */

/** 表信息tabs切换 */
const onTableTabsChange = async (key: any) => {
  tableActiveKey.value = key;
  console.log(key);
  if (key === "tableRelationships") {
    await loadTableRelationships(selectedTableObject.value.name || "");
  }
};

const getDsId = () => {
  const dsId = route.query.dsId;
  if (!dsId) throw new Error("dsId不能为空");
  const a = Number(dsId);
  if (Number.isNaN(a)) throw new Error("dsId不是数字");
  return a;
};

const getDsName = () => {
  const dsName = route.query.dsName as string;
  return dsName || "unknown";
};

type TableItemObject = {
  name: string;
  comment?: string;
  engine?: string;
  isSelected?: boolean;
};

const tableList = reactive({
  selectedKeys: [] as string[],
  openKeys: [] as string[],
  items: [] as TableItemObject[],
});

// type {
// id: Date.now() + Math.random(),
//       name: "",
//       type: "VARCHAR",
//       length: "255",
//       isPrimaryKey: false,
//       isAutoIncrement: false,
//       isNullable: true,
//       defaultValue: "",
//       comment: "",
//     }
type ColumnItem = {
  id: number;
  name: string;
  type: string;
  length: string;
  isPrimaryKey: boolean;
  isAutoIncrement: boolean;
  isNullable: boolean;
  defaultValue: string;
  comment: string;
};

const tableConfig = reactive<{
  dsId?: number;
  databaseName?: string;
  name?: string;
  newTableName?: string;
  comment?: string;
  engine?: string;
  columns?: ColumnItem[];
}>({});
const previewModelVisible = ref(false);
const onPreviewTableInfo = async () => {
  previewModelVisible.value = true;
};

const tablePreview = async (table) => {
  console.log(table);
};

const onTableAction = async (action: string, req: any) => {
  console.log(action, req);

  switch (action) {
    case "preview":
      onPreviewTableInfo();
      return "";
    case "save":
      const saveRes = await updateTable({
        dsId: req.dsId,
        databaseName: req.databaseName,
        tableName: req.name,
        newTableName: req.newTableName,
        fields: req.columns,
        tableArgs: {
          engine: req.engine,
          comment: req.comment,
        },
      });
      return saveRes.alterSQL;
    case "create":
      const createRes = await createTable({
        dsId: req.dsId,
        databaseName: req.databaseName,
        tableName: req.newTableName,
        fields: req.columns,
        tableArgs: {
          engine: req.engine,
          comment: req.comment,
        },
      });
      return createRes;
    case "execute":
      const executeRes = await execRawSql({
        dsId: req.dsId,
        databaseName: req.databaseName,
        sql: req.sql,
      });
      return executeRes;
    default:
      return "";
  }
};

const onTableInfo = async () => {
  console.log("onTableInfo:", tableConfig);
};

/** 表item点击事件,选择表操作 */
const onClickSelectOneTable = async (item: TableItemObject) => {
  fieldListRef.value?.clearData();
  item.isSelected = true;
  selectedTableObject.value = item;
  formModel.value = {
    ...formModel.value,
    ...item,
  };
  tableList.items.forEach((i) => {
    if (i.name !== item.name) {
      i.isSelected = false;
    }
  });
  console.log(item);
  // 加载该表格的字段列表
  loadTablesFieldList(item.name);
  loadTableInfo(item.name);
};

// 加载table info
const loadTableInfo = async (tableName: string) => {
  const dsId = getDsId();
  const tableInfo = await getTableInfo({
    dsId: dsId,
    databaseName: selectedDatabaseName.value,
    tableName,
  });

  const table = tableInfo.table;
  const fieldsList = tableInfo.fields.map((i: any) => {
    return {
      ...i,
      id: Date.now() + Math.random(),
      name: i.name,
      type: i.type,
      length: i.length,
      isPrimary: i.isPrimary,
      isAutoIncrement: i.isAutoIncrement,
      isNull: i.isNull,
      default: i.default,
      comment: i.comment,
      origin: JSON.parse(JSON.stringify(i)) as ColumnItem,
    };
  });

  tableConfig.dsId = dsId;
  tableConfig.databaseName = selectedDatabaseName.value;
  tableConfig.name = table.name;
  tableConfig.newTableName = table.name;
  tableConfig.comment = table.comment;
  tableConfig.engine = table.engine;
  tableConfig.columns = fieldsList as any;
  console.log(tableConfig);
};

const fieldListRef = ref<InstanceType<typeof FieldList> | null>(null);

const loadTablesFieldList = async (tableName: string) => {
  const dsId = getDsId();
  const fields = await getFieldsList({
    dsId: dsId,
    databaseName: selectedDatabaseName.value,
    tableName,
  });

  selectedTableFieldsList.value = fields;

  const fieldsList = fields.map((i) => {
    return {
      ...i,
      origin: JSON.parse(JSON.stringify(i)) as IFieldObject,
    };
  });

  fieldListRef.value?.setListData(fieldsList);
};

/** 保存表基本信息 */
const onDropTable = async (database: string, table: string) => {
  await dropTable({
    dsId: getDsId(),
    databaseName: database,
    tableName: table,
  });
  message.success("删除成功");
};

/** 创建表按钮，添加一个Tab，专用于创建表 */
const onCreateTableClick = () => {
  const dsId = getDsId();
  const databaseName = selectedDatabaseName.value;
  if (!dsId || !databaseName) {
    message.error("请选择数据库再操作");
    return;
  }

  const panel: paneObject = {
    type: "tableCreator",
    title: databaseName + " - 新建表",
    // content: 'Content of new Tab',
    key: getRandomKey(),
    closable: true,
    data: {
      dsId: getDsId(),
      databaseName: selectedDatabaseName.value,
      name: "",
      comment: "",
      engine: "",
      columns: [],
    },
  };
  panes.value.push(panel);
  activeTabKey.value = panel.key;
};

const onCloseCreateTable = (pane: paneObject) => {
  console.log("onCloseCreateTable: " + pane.key);
  panes.value = panes.value.filter((p) => p.key !== pane.key);
  console.log("onCloseCreateTable: " + JSON.stringify(panes.value));
  // 并激活最后一个tab
  activeTabKey.value = "tableInfo";
};

// init exec
initGetDatabasesList();

// Mock API functions

const onDatabaseAction = async (action: string, req: any) => {
  console.log(action, req);
  switch (action) {
    case "getTables":
      const database = req.database;
      console.log(`Fetching tables for: ${database}`);

      const list = (await getTableList({
        dsId: getDsId(),
        databaseName: database,
      })) as any;

      console.log(list);
      if (!list || !list.tables || list.tables.length === 0) {
        return [];
      }

      list.tables.forEach((item) => {
        item.title = item.name;
        item.key = `${database}-${item.name}`;
        item.type = "table";
        item.isLeaf = false;
      });

      return list.tables;
    case "getFields":
      console.log(`Fetching fields for: ${req.database}-${req.table}`);

      const fieldList = (await getFieldsList({
        dsId: getDsId(),
        databaseName: req.database,
        tableName: req.table,
      })) as any;

      console.log(fieldList);
      if (!fieldList || fieldList.length === 0) {
        return [];
      }

      fieldList.forEach((item) => {
        item.title = item.name;
        item.key = `${req.table}-${item.name}`;
        item.type = "field";
        item.isLeaf = true;
      });

      return fieldList;
    case "DELETE_TABLE":
      await onDropTable(req.database, req.table);
      return "";
    case "CREATE_TABLE":
      console.log(`Fetching fields for: ${req.databaseName}-${req.tableName}`);
    default:
      return "";
  }
};

// Event handlers
const handleLoadData = (payload) => {
  console.log("Load data:", payload);
};

const handleContextMenu = (payload) => {
  console.log("Context menu click:", payload);
  switch (payload.action) {
    case "DELETE_TABLE":
      const database = payload.data.database;
      const table = payload.name;
      onDropTable(database, table);
      break;
    default:
      break;
  }
};

// ================ 查询开始 ====================
/** 查询结果，用于显示 */
const onEditAction = async (action: string, req: any) => {
  console.log("onEditAction:", action, req);

  switch (action) {
    case "complete":
      const res = await lspComplete({
        dsId: getDsId(),
        databaseName: req.database,
        input: req.input,
        line: req.line,
        col: req.col,
      });

      console.log(res);
      return res;

    case "query":
      const queryRes = await execRawSql({
        dsId: req.dsId,
        databaseName: req.database,
        sql: req.sql,
      });

      return queryRes;
    default:
      return [];
  }
};

// ================ 查询结束 ====================
</script>

<style scoped lang="less">
.workspace-box {
  :deep(.field-plus-box) {
    // padding-left: 16px;
    display: flex;
    position: relative;

    .plus-box {
      width: 22px;
      margin-right: 4px;
      opacity: 0;
      color: #1890ff;
      font-size: 22px;
      text-align: left;
      cursor: pointer;
    }
  }

  /* 实现row hover 显示添加图标 */
  :deep(.field-row-hover) {
    &:hover {
      .plus-box {
        opacity: 1;
      }
    }
  }
}

:deep(.left-database-list .ant-menu-item, .left-database-list .ant-menu-submenu-title) {
  padding: 8px 16px; /* 自定义的内边距 */
  font-size: 14px; /* 自定义的字体大小 */
  height: 20px; /* 自定义高度 */
  line-height: 20px; /* 控制文本垂直对齐 */
}

// table-list-box背景色为纯白色
:deep(.table-list-box) {
  background-color: #fff;
}

// table-list-box的padding设置为16px
:deep(.table-list-box .ant-list-item) {
  padding: 8px 10px; /* 自定义的内边距 */
  font-size: 10px; /* 自定义的字体大小 */
  // height: 20px;      /* 自定义高度 */
  line-height: 20px; /* 控制文本垂直对齐 */
}

/* 统一 pane 内容样式 */
.pane-content {
  height: 100%;
  // padding: 16px;
  display: flex;
  border: 1px solid #ddd;
  background-color: #f5f5f5;
  font-size: 16px;
  color: #333;
  transition: background-color 0.3s, color 0.3s;
}

/* 左右 pane 的自定义样式 */
/* 左侧面板样式 */
.left-pane {
  background-color: #ffffff;

  /* 内部可滚动区域 */
  .scrollable-content {
    height: 100%; /* 确保滚动区域占满高度 */
    overflow-y: auto; /* 启用垂直滚动条 */
    padding-right: 8px; /* 留出滚动条的空间 */
    box-sizing: border-box;

    /* 滚动条样式优化 */
    &::-webkit-scrollbar {
      width: 8px;
    }
    &::-webkit-scrollbar-thumb {
      background-color: #1890ff;
      border-radius: 4px;
    }
    &::-webkit-scrollbar-track {
      background-color: #f0f0f0;
    }
  }
}
.right-pane {
  background-color: #ffffff;
  // &:hover {
  //   background-color: #ffe58f;
  //   color: #ad6800;
  // }
}

/* Splitpanes 样式优化 */
.splitpanes {
  height: 100%;
  border: none;

  /* 调整拖拽条样式 */
  .splitpanes__splitter {
    background-color: #1890ff;
    width: 5px;
    cursor: ew-resize;
    transition: background-color 0.3s;

    &:hover {
      background-color: #40a9ff;
    }
  }
}
</style>
